package com.sailors.common.task.provider.application.event.listener;

import com.alibaba.fastjson.JSON;
import com.sailors.common.task.provider.application.event.event.FileTaskCreateEvent;
import com.sailors.common.task.provider.domian.model.entity.FileTaskEntity;
import com.sailors.common.task.provider.domian.service.IFileTaskService;
import com.sailors.common.task.provider.faced.model.enums.TaskDelayedLevelEnum;
import com.sailors.common.task.provider.infra.design.common.enums.BussinessBaseEnumUtil;
import com.sailors.common.task.provider.infra.system.config.task.CommonDelayQueueTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;

/**
 * Sign event listener
 *
 * @description: 监听器
 * @author: cyj
 * @date 2022 -11-23 14:23:52
 */
@Component
@Slf4j
public class FileTaskEventListener {

    @Autowired
    @Qualifier("fileTaskDelayQueue")
    public DelayQueue<CommonDelayQueueTask<Long>> delayQueueTasks;

    @Autowired
    private IFileTaskService fileTaskService;

    /**
     * Delayed handle *
     *
     */
    @EventListener({FileTaskCreateEvent.class})
    @Async
    public void delayedHandle(FileTaskCreateEvent fileTaskCreateEvent) {
        FileTaskEntity fileTaskEntity = fileTaskCreateEvent.getFileTaskEntity();
        log.info("接受文件任务创建事件，处理延时校验：{}", JSON.toJSONString(fileTaskEntity.getCommonProperty()));
        TaskDelayedLevelEnum taskDelayedLevelEnum = BussinessBaseEnumUtil.getByCode(fileTaskEntity.getCommonProperty().getDelayedCheck(), TaskDelayedLevelEnum.class);
        if (null == taskDelayedLevelEnum || TaskDelayedLevelEnum.NONE == taskDelayedLevelEnum) {
            log.info("taskDelayedLevelEnum空或0，不处理延时校验！");
            return;
        }
        delayQueueTasks.add(new CommonDelayQueueTask<Long>(fileTaskEntity.getIdentify().getId(), taskDelayedLevelEnum.delayTime, (taskId) -> {
            fileTaskService.delayedFailed(taskId);
        }));
        log.info("接受文件任务创建事件，成功添加到延时队列");
    }
}
